import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:t2app/src/Config.dart';
import 'package:t2app/src/common/AppData.dart';
import 'package:t2app/src/util/log_util.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import '../../common/Tool.dart';
import '../../entity/User.dart';

class YesServer_Chat_View extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return  new ChatViewState();
  }


}

/**
 * 纯demo项目  不保留聊天数据
 * 后续拥有和在相关节点保留聊天数据
 */
class ChatViewState extends State<YesServer_Chat_View>{

  //模拟用户id
  User? _user = AppData.user;

  //在线人数
  String _online = "1";
  String _separation = "@@";
  //聊天数据
  var _list = [];
  //发送框
  TextEditingController _textController = TextEditingController();

  ScrollController _controller = ScrollController();

  WebSocketChannel?  _channel;
  bool _websocketEnd = false;

  StreamController<String> _streamController =  StreamController<String>();

  ChatViewState(){
    _init();
  }

  void _init(){
      //初始化用户信息
      if(_user == null) {
        _user = new User();
      }
      _connect();
  }

  _connect(){
    _channel = new IOWebSocketChannel.connect(Config.WEBSOCKET_URL, connectTimeout:new Duration(seconds:3));
    var msg = "init@@${_user!.id}";
    //初始化之后发送用户信息过去，服务器端可以通过连接channelId绑定用户信息
    _channel?.sink.add(msg);

    _channel?.stream.listen((message) {
      EasyLoading.dismiss();

      if (message.startsWith("online$_separation")) {
        LogUtil.p("channel收到消息[在线人数]:"+message);

        setState(() {
          _online = message.split(_separation)[1];
        });
      } else {
        LogUtil.p("channel收到消息[普通]:"+message);
        //正常消息
        List<String> msg = message.split(_separation);
        setState(() {
          _list.add({"sendId":msg[0],"name":msg[1],"portrait":msg[2],"msgType":int.parse(msg[3]),"sendText":msg[4],"friendlyTime":"刚刚"});
        });
        //跳转到最底部
        new Timer(new Duration(milliseconds:200), (){
          _controller.jumpTo(_controller.position.maxScrollExtent);
        });
      }
    },onError: (error){
      Tool.showToast("websocket服务连接异常");
    }, onDone: (){
          if(!_websocketEnd){
            print("channel被关闭尝试重新连接...");
            _connect();
          }
        }
    );
  }

  @override
  void initState() {
    //获取聊天信息列表
    super.initState();
  }

  /*
  必须再state中关闭连接
   */
  @override
  void dispose(){
    EasyLoading.dismiss();
    _websocketEnd=true;
    _channel?.sink.close();//这里关闭会触发 done事件导致setState() called after dispose()错误,设置一个全局标签_websocketEnd
    _streamController.close();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    //跳转到最底部
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      new Timer(new Duration(milliseconds:200), (){
        _controller.jumpTo(_controller.position.maxScrollExtent);
      });
    });

    return new Scaffold(
              appBar: Config.APP_BAR(title: new Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  new Text("聊天室"),
                  new Text("${_online}人在线", style: TextStyle(fontSize: 14),)
                ],
              )),
              body: new Stack(
                children: [
                  new ListView.builder(
                    controller: _controller,
                    padding: new EdgeInsets.fromLTRB(10,10,10,60),
                    itemCount: _list.length,
                    itemBuilder: (BuildContext context,int index){
                      return new Column(
                        children: [
                          _list[index]['sendId']==_user?.id.toString()?_rightContainer(index):_leftContainer(index)
                        ],
                      );
                    },
                  ),
                  new Positioned(
                    bottom: 0,
                    width: MediaQuery.of(context).size.width,
                    child:
                        new Container(
                          width: MediaQuery.of(context).size.width,
                          color: Config.THEME.primaryColorLight,
                          padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
                          child: new TextField(
                            maxLength:240,
                            textInputAction: TextInputAction.done,
                            maxLines: 4,
                            minLines: 1,
                            controller:  _textController,
                            decoration: InputDecoration(
                              hintText: '请输入内容',
                              fillColor: Colors.white,
                              suffixIcon:new IconButton(
                                  icon: new Icon(Icons.send),
                                  onPressed: (){
                                    if(_textController.text == ''){
                                      return;
                                    }
                                    var param={"sendId":_user?.id,"sendText":_textController.text,"msgType":1};

                                    var sendmsgstr=[param["sendId"],_user?.nickname,_user?.head_img,param["msgType"],param["sendText"]];

                                    _channel?.sink.add(sendmsgstr.join("$_separation"));

                                    _textController.text = "";
                                    Tool.showToast("发送成功");
                                    //取消焦点
                                    FocusScope.of(context).requestFocus(FocusNode());
                                  }
                              )
                            ),
                          ),
                        ),
                    )
                ],
              ),
            );
  }

  _rightContainer(int index){
    var data = _list[index];
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              new Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  new Text(data['name']+"  ",style: TextStyle(color: Config.THEME.primaryColorDark),),
                  new Text(data['friendlyTime']+"  ",style: TextStyle(color:Colors.grey),)
                ],
              ),
              ClipOval(
                child:  CachedNetworkImage(
                  width: 40,
                  height: 40,
                  imageUrl: data["portrait"],
                ),
              ),
            ],
          ),
          data['msgType']==1?Container(
            margin: EdgeInsets.fromLTRB(5, 20, 45,20),
            child: new Text(data['sendText'], style: TextStyle(fontSize: 20),),
          ):Container(),
          index==_list.length-1?new Center(
            child: new Text("---人家也是有底线的---",style: TextStyle(fontSize: 12,color: Config.THEME.primaryColorLight),),
          ):new Text("")
        ],
      ),
    );
  }
  _leftContainer(int index) {
    var data = _list[index];
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              ClipOval(
                child: CachedNetworkImage(
                  width: 40,
                  height: 40,
                  imageUrl: data["portrait"],
                ),
              ),
              new Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  new Text("  " + data['name'],
                    style: TextStyle(color: Config.THEME.primaryColorDark),),
                  new Text("  " + data['friendlyTime'],
                    style: TextStyle(color: Colors.grey),)
                ],
              )
            ],
          ),
          data['msgType']==1?Container(
            margin: EdgeInsets.fromLTRB(45, 20, 5, 20),
            child: new Text(data['sendText'], style: TextStyle(fontSize: 20),),
          ):Container(),
          index==_list.length-1?new Center(
            child: new Text("---人家也是有底线的---",style: TextStyle(fontSize: 12,color: Config.THEME.primaryColorLight)),
          ):new Text("")
        ],
      ),
    );
  }
}
